import SwiftUI

extension Color {
    init?(hex: String) {
        var hexString = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

        // 去掉开头的 "#" 或 "0X"
        if hexString.hasPrefix("#") {
            hexString.removeFirst()
        } else if hexString.hasPrefix("0X") {
            hexString = String(hexString.dropFirst(2))
        }

        // 只支持 6 位 RGB 或 8 位 ARGB
        var rgbValue: UInt64 = 0
        guard Scanner(string: hexString).scanHexInt64(&rgbValue) else { return nil }

        switch hexString.count {
        case 6: // RGB
            let r = Double((rgbValue & 0xFF0000) >> 16) / 255.0
            let g = Double((rgbValue & 0x00FF00) >> 8) / 255.0
            let b = Double(rgbValue & 0x0000FF) / 255.0
            self.init(red: r, green: g, blue: b)
        case 8: // ARGB
            let a = Double((rgbValue & 0xFF000000) >> 24) / 255.0
            let r = Double((rgbValue & 0x00FF0000) >> 16) / 255.0
            let g = Double((rgbValue & 0x0000FF00) >> 8) / 255.0
            let b = Double(rgbValue & 0x000000FF) / 255.0
            self.init(red: r, green: g, blue: b, opacity: a)
        default:
            return nil
        }
    }
    func darken(_ amount: CGFloat) -> Color {
        let uiColor = UIColor(self)

        var hue: CGFloat = 0
        var saturation: CGFloat = 0
        var brightness: CGFloat = 0
        var alpha: CGFloat = 0

        if uiColor.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
            let newSaturation = min(max(saturation * (1 + amount), 0), 1)
            let newBrightness = min(max(brightness * (1 - amount), 0), 1)
            let darkened = UIColor(hue: hue, saturation: newSaturation, brightness: newBrightness, alpha: alpha)
            return Color(darkened)
        } else {
            return self // fallback if getHue fails
        }
    }
}
